package com.hxx.exception;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 可以为所有的 REST 控制器提供统一的错误处理机制
 * @RestControllerAdvice 是 Spring 框架中的一个注解，
 *     它结合了 @ControllerAdvice 和 @ResponseBody 的功能
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, String>> handleBusinessException(RuntimeException e) {
        Map<String, String> response = new HashMap<>();
        response.put("code", "BUSINESS_ERROR");
        response.put("message", e.getMessage());
        return ResponseEntity.badRequest().body(response);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, String>> handleException(Exception e) {
        Map<String, String> response = new HashMap<>();
        response.put("code", "SYSTEM_ERROR");
        response.put("message", e.getMessage());
        return ResponseEntity.internalServerError().body(response);
    }
}
